package ru.urfc.portal.operations;

import java.util.Arrays;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import ru.urfc.portal.dao.BasePersistence;
import ru.urfc.portal.dao.Pair;
import ru.urfc.portal.dao.TmpContragentDao;
import ru.urfc.portal.dao.filter.Filter;
import ru.urfc.portal.dao.filter.Operator;
import ru.urfc.portal.dao.impl.BaseUtil;
import ru.urfc.portal.model.Client;
import ru.urfc.portal.model.Branch;
import ru.urfc.portal.model.NotificationSettings;
import ru.urfc.portal.model.TmpContragent;
import ru.urfc.portal.model.accounting.Contragent;

@Stateless
public class ClientsSynchronizer extends BaseUtil {
	
	@EJB BasePersistence basePersistence;
	@EJB TmpContragentDao clientDao;
	
	public ClientsSynchronizer() {
		// TODO Auto-generated constructor stub
	}
	public ClientsSynchronizer(BasePersistence basePersistence,
			TmpContragentDao clientDao) {
		super();
		this.basePersistence = basePersistence;
		this.clientDao = clientDao;
	}

	public static class BranchContragents extends Pair<Branch, List<Contragent>> { 
		public BranchContragents(Branch branch, List<Contragent> contragents) {
			super(branch, contragents);
		}
	}

	public List<TmpContragent> synchronize(BranchContragents... branchesContragents) {
		return synchronize(Arrays.asList(branchesContragents));
	}
	
	public List<TmpContragent> synchronize(List<BranchContragents> branchesContragents) {
		Long operationId = clientDao.generateOperationId();
		
		for (BranchContragents branch: branchesContragents) { 
			clientDao.createTmpContragents(operationId, branch.getFirst(), branch.getSecond());
		}
		clientDao.updateTmpContragents(operationId);
		List<TmpContragent> newClients = basePersistence.find(TmpContragent.class, new Filter(
				"operationId", operationId).add("client", Operator.IS_NULL));
		createClients(newClients, exactlyOne(basePersistence.find(NotificationSettings.class, "global", true)));
		Filter resultFilter = new Filter("operationId", operationId);
		resultFilter.addFetch("client");
		return basePersistence.find(TmpContragent.class, resultFilter);
	}

	private void createClients(List<TmpContragent> tmpContragents, NotificationSettings global) {
		for (TmpContragent contragent: tmpContragents) {
			Client client = basePersistence.persist(new Client(
					null, contragent.getContragentId(), contragent.getBranch(), false, false));
			client.setNotificationSettings(new NotificationSettings(global));
			contragent.setClient(client);
		}
	}

}
